#include "simpleXml.h"
#include<fstream>
#include "xmlFunction.h"
using std::ifstream;
bool simpleXml::loadFile(const char *pathName)
{
	ifstream fin;
	fin.open(pathName);
	if(!fin)
	{
		return false;
	}
	bool isbef=false,isin=false;
	string tmpstr; 
	while(getline(fin,tmpstr))
	{
		tmpstr=xmlFunctions::UTF8ToGB(tmpstr.data());
		for(UI i=0;i<tmpstr.size();i++)
		{
			if(!xmlFunctions::isSpace(tmpstr[i]))
			{
				if(tmpstr[i]=='<'&&(!isbef))
				{
					isin=true;
					
				}
				if(tmpstr[i]=='>'&&(!isbef))
				{
					isbef=true;
					isin=false;
					continue;
				} 
				if(isin) continue;
				this->xmlVal+=tmpstr[i];
			//	printf("%c",char(ch));
			}
		}	
	}
	this->xmlSize = xmlVal.size();
	return true;
}
simpleXml::simpleXml()
{
	this->charset="/undefine/";
	this->version="/undefine/"; 
	this->xmlVal="/undefine/";
	this->root=NULL;
}
string xmlNode::getName()
{
	return this->name;
}
string xmlNode::getVal()
{
	return this->val;
}
xmlNode::xmlNode(string val,string name)
{
	this->val=val;
	this->name=name;
}
xmlNode* simpleXml::getRoot()
{
	if(root!=NULL) return root;
	if(xmlVal=="/undefine/") exit(0);
	string name=xmlFunctions::getname(xmlVal,xmlSize);
	string val=xmlFunctions::getval(xmlVal,xmlSize);
	return new xmlNode(val,name);
}

vector<xmlNode*> xmlNode::getChirld()
{
	if(Chirld.size()!=0) return (this->Chirld);
	bool isin=false;
	string lastname="",tmpstr="";
	int lastf=0;
	for(UI i=0;i<val.size();i++)
	{
		if(val[i]=='<') isin=true;
		else if(val[i]=='>')
		{
			isin=false;
			if(lastname==tmpstr.substr(1,tmpstr.size()))
			{
				tmpstr=val.substr(lastf,i+1);
				Chirld.push_back(new xmlNode(xmlFunctions::getval(tmpstr,tmpstr.size()),lastname));
				tmpstr="";
				lastname="";
			}else
			{
				lastname=tmpstr;
				tmpstr="";
			}
		} 
		else if(isin) tmpstr+=val[i];
	}
	return Chirld;
}
xmlNode::~xmlNode()
{
	for(UI i=0;i<Chirld.size();i++)
	{
		delete Chirld[i];
	}
	Chirld.clear();
	//val=name="undefine";
}
void simpleXml::clear()
{
	delete root;
	charset="/undefine/",xmlVal="/undefine/",xmlSize=0,version="/undefine/";
} 
simpleXml::~simpleXml()
{
	clear();
}
